package com.prg.action.app;

import com.prg.model.easyui.Grid;
import com.prg.model.easyui.Json;
import com.prg.service.impl.BaseServiceImpl;
import com.prg.util.HqlFilter;
import com.prg.util.JsonUtil;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 15-1-5
 * Time: 下午7:04
 * To change this template use File | Settings | File Templates.
 */
@Controller
public class BaseController<T> {
    protected int page = 1;// 当前页
    protected int rows = 10;// 每页显示记录数


    /**
     * 查找分页后的grid
     */
    public void grid(HttpServletRequest request, HttpServletResponse response, BaseServiceImpl service) {
        Grid grid = new Grid();
        HqlFilter hqlFilter = new HqlFilter(request);
        grid.setTotal(service.countByFilter(hqlFilter));
        grid.setRows(service.findByFilter(hqlFilter, page, rows));
        JsonUtil.writeJson(response, grid);
    }

    /**
     * 保存一个对象
     */
    public void save(HttpServletResponse response, BaseServiceImpl service, T data) {
        Json json = new Json();
        if (data != null) {
            service.save(data);
            json.setSuccess(true);
            json.setMsg("新建成功！");
        }
        JsonUtil.writeJson(response, json);
    }

    public void edit(HttpServletResponse response, BaseServiceImpl service, T data) {
        Json json = new Json();
        if (data != null) {
            service.update(data);
            json.setSuccess(true);
            json.setMsg("编辑成功！");
        }
        JsonUtil.writeJson(response, json);
    }

    /**
     * 删除 一个对象
     */
    public void delete(HttpServletResponse response, BaseServiceImpl service, T data) {
        Json json = new Json();
        if (data != null) {
            service.delete(data);
            json.setSuccess(true);
            json.setMsg("删除成功！");
        }
        JsonUtil.writeJson(response, json);
    }


}